<?php
namespace jy_security;
defined('BY_JYA') or exit('error');
/*
	防伪批次
*/
class batch extends \plugin{
	function add_batch($goodsid=0,$num=0,$type=0,$remark=''){
		$setting=$this->plugin_setting('secury');
		if(!$setting['pre'] || !$setting['goods'] ||  !$setting['batch'] || !$setting['serial'] || !$setting['code'] || !$setting['garble']){
			exi('请先设置好-参数设置--防伪码前缀/批号位数/流水号位数/校验码位数/混淆码位数！','error');
		}
		$goods=pdo_get('jy_security_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$goodsid));
		if(!$goods){
			//exi('指定商品不存在！','error');
		}
		$goods_code=$goods['code']?:'166668888';
		$seckey=random(32);
		$batch_code=rand(pow(10,($setting['batch']-1)), pow(10,$setting['batch'])-1);
		$security_codes=$this->made_security_code($goods_code,$batch_code,$num,$seckey);
		$show_code=array_shift($security_codes);
		$string='';
		switch($type){
			case 1:
				$string=implode("\r\n",$security_codes);
				break;
			case 2:
				foreach($security_codes as $code){
					$string.=$this->format($code)."\r\n";
				}
				break;
			case 3:
				foreach($security_codes as $code){
					$string.=custom_url('jy_security/search/main/code='.$code,true)."\r\n";
				}
				break;
				
		}
		if(!$string){
			exi('生成失败！','error');
		}
		$filename = ROOT_AT.random(10).".zip";
		$zip = new \ZipArchive();
		$zip->open($filename,\ZipArchive::CREATE);
		$zip->addFromString('code.txt',$string);
		$zip->close();
		$zip=cfc('files')->source_save($filename,'zip','zip');
		//print_r($zip);exit();
		@unlink($filename);
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'goods_id'=>$goodsid,
			'goods_code'=>$goods_code,
			'seckey'=>$seckey,
			'code'=>$batch_code,
			'status'=>1,
			'type'=>$type,
			'remark'=>$remark,
			'num'=>$num,
			'createtime'=>TIMESTAMP,
			'code_file'=>$zip,
			'show_code'=>$show_code,
		);
		pdo_insert('jy_security_batch',$data);
		return $zip;	
	}
	function made_security_code($goods_code='',$batch_code='',$serial_code=0,$seckey=''){
		$setting=$this->plugin_setting('secury');//获取参数设置
		$security_codes=array();
		for($i=0;$i<=$serial_code;$i++){
			$temp=$setting['pre'].sprintf("%'0{$setting['goods']}s",$goods_code).sprintf("%'0{$setting['batch']}s",$batch_code).sprintf("%'0{$setting['serial']}s",$i);
			$check_code=cfc('tools')->create_check_code($temp,$seckey,$setting['code']);//校验码
			$garble_code=random($setting['garble'],true);//混淆码
			$security_code=$temp.$check_code.$garble_code;
			//$string.=custom_url('jy_security/search/main/code='.$security_code,true)."\n";
			$security_codes[]=$security_code;
		}
		return $security_codes;
	}
}